﻿/******************************************************************************
 * Name         : Worker.cpp
 * Author       : 671643387
 * Date         : 2015年9月11日
 * Description  :
 *****************************************************************************/

#include <boost/bind.hpp>
#include "Common.h"
#include "Worker.hpp"
using namespace dev;

extern int gsFrameTime;

Worker::Worker(int conn)
: idGen_(0)
, conns_(0)
, eventLoop_()
{
    eventLoop_.setRemoveSocketCallback(
        boost::bind(&Worker::onSocketRemovedFromLoop, this, _1));
    eventLoop_.setFrameTime(gsFrameTime);

    for (int x = 0; x < conn; ++x)
    {
        int id = ++idGen_;
        ClientPtr client = ClientPtr(new Client(id, eventLoop_));
        if (client)
        {
            if (!client->open())
            {
                continue;
            }
            
            inc_conn();
            ++conns_;
            clients_[id] = client;
        }
    }

    if (conns_ == 0)
    {
        std::cout << "worker initialize failed" << std::endl;
        throw std::exception();
    }
}

Worker::~Worker()
{

}

void Worker::stop()
{
    ClientMap::iterator it = clients_.begin();
    for (; it != clients_.end(); ++it)
    {
        it->second->shutdown();
    }
}

void Worker::run()
{
    eventLoop_.run();
}

void Worker::onSocketRemovedFromLoop(dev::net::Socket* sock)
{
    int id = sock->getUserDataInt();
    ClientPtr client = clients_[id];
    if (client)
    {
        clients_.erase(id);
        client->close();
    }

    if (clients_.empty())
    {
        eventLoop_.stop();
    }
}